package com.datastructures2.背包队列栈;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author MaoLin Wang
 * @date 2020/2/2819:26
 */
public class Bag<Item> implements Iterable<Item> {

    private Node<Item> root;
    private int n = 0;

    public void add(Item item){
        Node<Item> old=root;
        root=new Node<>();
        root.val=item;
        root.next=old;
        this.n++;
    }

    public boolean isEmpty(){
        return root==null;
    }
    public int size(){
      return   this.n;
    }
    @Override
    public Iterator<Item> iterator() {
        return new ListIterator<>(this.root);
    }

    /**
     * 迭代器
     * @param <Item>
     */
    private class ListIterator<Item> implements Iterator<Item>{

        private Node<Item> current;

        public ListIterator(Node<Item> current) {
            this.current = current;
        }

        @Override
        public boolean hasNext() {
            return current!=null;

        }

        @Override
        public Item next() {
            if (hasNext()){
                Item val = this.current.val;
                this.current=this.current.next;
                return val;
            }else {
                throw new NoSuchElementException("元素不存在");
            }
        }

    }
    private static class Node<Item>{
        Item val;
        Node<Item> next;

    }

    public static void main(String[] args) {
        Bag<Integer> bag = new Bag<>();
        bag.add(1);
        bag.add(2);
        bag.add(3);
        bag.add(4);
        Iterator<Integer> iterator = bag.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}
